package cn.tedu.baking.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法的授权检测功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //配置黑名单
        String[] urls = {"/admin.html","/personal.html",
                "/postArticle.html","/content-management.html",
                "/**/delete","/**/update","/**/add-new"
                };
        http.authorizeHttpRequests()     //请求认证管理
                .mvcMatchers(urls).authenticated() //匹配上面的所有路径 必须通过登录认证后才能放行
                .anyRequest().permitAll(); //其它所有路径  直接放行
        //调用框架提供的登录页面
//        http.formLogin();
        //配置没有登录的时候跳转到自己的登录页面
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                //没有登录 并请求了需要登录的资源时执行此处代码
                response.sendRedirect("/login.html");
            }
        });
        //禁用跨域攻击的防御
        http.csrf().disable();
    }
    //配置认证管理器
    @Bean  //添加此注解 是为了能够通过Spring框架自动装配
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //设置不加密
//        return NoOpPasswordEncoder.getInstance();
        //返回一个BCrypt密码编码器  哈希加密算法(单向加密,不可逆)
        return new BCryptPasswordEncoder();
    }

}

